#!/bin/bash
set -ex  # 出现错误立即退出
PROJECT_NAME="Bp"
BACKEND_NAME="${PROJECT_NAME}Backend"
FRONTEND_NAME="${PROJECT_NAME}Web"
REPO_URL="https://gitee.com/biaozhun/bp.git"
TARGET_DIR="${pwd}/ptl-bp"
DOCKER_BASE_DIR="/app/${PROJECT_NAME}"
DOCKER_BASE_DIR_OLD="/docker/${PROJECT_NAME}"
[ -d "$DOCKER_BASE_DIR_OLD" ] && [ ! -d "$DOCKER_BASE_DIR" ] && mv -f "$DOCKER_BASE_DIR_OLD" "$DOCKER_BASE_DIR" 2>/dev/null || true
APP_ENV="ggok"
# Functions
clone_or_update_repo() {
    local repo_dir="$1"
    if [ ! -d "${repo_dir}/.git" ]; then
        git clone "$REPO_URL" "$repo_dir"
    fi
    cd "$repo_dir"
    git reset --hard && git pull
}

setup_data_dir() {
    if [ ! -d "$DOCKER_BASE_DIR" ]; then
        mkdir -p ${DOCKER_BASE_DIR}/data/{upload,log}
        chmod 755 "$DOCKER_BASE_DIR"
    fi
}

deploy_backend() {
    echo "Deploying backend..."
    clone_or_update_repo "$TARGET_DIR"
    cd
    cd "${TARGET_DIR}/${BACKEND_NAME}"

    docker build -t "${PROJECT_NAME,,}-backend:latest" .
    docker stop "$BACKEND_NAME" || true
    docker rm "$BACKEND_NAME" || true

    setup_data_dir

    docker run -d \
        --name "$BACKEND_NAME" \
        --restart=unless-stopped \
        -e TZ=Asia/Shanghai \
        -e ACTIVE_PROFILE=${APP_ENV} \
        -e JAVA_OPTS="-Xms512m -Xmx512m" \
        -p 20728:20728 \
        -v "${DOCKER_BASE_DIR}/data:/app/data" \
        "${PROJECT_NAME,,}-backend:latest"
}

deploy_frontend() {
    echo "Deploying frontend..."
    clone_or_update_repo "$TARGET_DIR"
    cd
    cd "${TARGET_DIR}/${FRONTEND_NAME}"

    docker build -t "${PROJECT_NAME,,}-frontend:latest" --build-arg APP_ENV=${APP_ENV} .
    docker stop "$FRONTEND_NAME" || true
    docker rm "$FRONTEND_NAME" || true

    docker run -d \
        --name "$FRONTEND_NAME" \
        --restart=unless-stopped \
        -p 10728:80 \
        "${PROJECT_NAME,,}-frontend:latest"
}

# Main execution
if [ -z "$1" ] || [ "$1" == "backend" ]; then
    deploy_backend
fi

if [ -z "$1" ] || [ "$1" == "web" ]; then
    deploy_frontend
fi